package com.maori.languageapp.discover.word;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import com.maori.languageapp.R;
import com.maori.languageapp.consts.ImageLoader;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Maori_Discover_Word_Details_Adapter extends BaseAdapter {
	private static final String TAG = null;
	// Declare Variables
	Context context;
	LayoutInflater inflater;
	ArrayList<HashMap<String, String>> data;
	ImageLoader imageLoader;
	Button setDefAction;
	Button setLikeAction;
	int timeoutConnection = 5000;
	HttpParams httpParameters = new BasicHttpParams();
	String SynUserID,SynNodeId,SynUserLikedSyn,SynParentNodeId;
	InputStream is = null;
	StringBuilder sb = null;
	String result;
	int LikeActive = 0;
	int LikeCounter;
	ArrayList<HashMap<String, String>> arraylist;
	JSONArray jsonarray;
	
	public Maori_Discover_Word_Details_Adapter(Context context,
			ArrayList<HashMap<String, String>> arraylist) {
		this.context = context;
		data = arraylist;
		imageLoader = new ImageLoader(context);

	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		// Declare Variables
		TextView maori_synonym_title, english_synonym_title,first_name,last_name;
		ImageView flag; // Loading User Images (Future use)
		Button dicover_location,display_dialect;
		
		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View itemView = inflater.inflate(R.layout.languageapp_discover_synonyms,
				parent, false);
		
		// Get the position from the results
		HashMap<String, String> resultp = new HashMap<String, String>();
		resultp = data.get(position);
		//flag = (ImageView) itemView.findViewById(R.id.mem_discover_img);

		//Display Synonyms
		maori_synonym_title = (TextView) itemView.findViewById(R.id.maori_synonym_title);
		english_synonym_title= (TextView) itemView.findViewById(R.id.english_synonym_title);
		dicover_location= (Button) itemView.findViewById(R.id.dicover_location);
		display_dialect= (Button) itemView.findViewById(R.id.display_dialect);
		first_name= (TextView) itemView.findViewById(R.id.first_name);
		last_name= (TextView) itemView.findViewById(R.id.last_name);
		flag = (ImageView) itemView.findViewById(R.id.imggriditem);
		
		setDefAction = (Button) itemView.findViewById(R.id.setDefAction);
		setLikeAction = (Button) itemView.findViewById(R.id.setLikeAction);
		
		// Capture position and set results to the TextViews
		maori_synonym_title.setText(resultp.get(Maori_Discover_Word_Details.Description_a));
		english_synonym_title.setText(resultp.get(Maori_Discover_Word_Details.Description_b));
		dicover_location.setText(resultp.get(Maori_Discover_Word_Details.SYNcurrent_location));
		display_dialect.setText(resultp.get(Maori_Discover_Word_Details.SYNtribe));
		first_name.setText(resultp.get(Maori_Discover_Word_Details.first_namesuser) + " " + resultp.get(Maori_Discover_Word_Details.last_nameuser));
		last_name.setText(resultp.get(Maori_Discover_Word_Details.SYNrole));
		String UIDuser = resultp.get(Maori_Discover_Word_Details.UIDuser); 
		String SYNNID = resultp.get(Maori_Discover_Word_Details.SYNNID); 
		String SYNParentNID = resultp.get(Maori_Discover_Word_Details.SYNParentNID); 
		String SYNUserLikedSyn = resultp.get(Maori_Discover_Word_Details.SYNUserLikedSyn); 
		
		if(SYNUserLikedSyn.equals("0")){
			setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_inactive,
					0, 0, 0);
		}
		else{
			setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_h,
					0, 0, 0);
		}
		Log.d("*********************","ACTIVE : " + LikeActive + "@@@@@"+  SYNUserLikedSyn) ;	
		Log.v(TAG, "***XXX LIKES*****:" + resultp.get(Maori_Discover_Word_Details.TotalsLikesSyn));
		setLikeAction.setText("Like(" + resultp.get(Maori_Discover_Word_Details.TotalsLikesSyn)+")");
		
		imageLoader.DisplayImage(resultp.get(Maori_Discover_Word_Details.userimageuser),
				flag);
		
		setLikeAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				HashMap<String, String> resultp = new HashMap<String, String>();
				resultp = data.get(position);
				Log.v("TAG","ACTIVE PRESS : " + LikeActive);
				
				SynUserID = resultp.get(Maori_Discover_Word_Details.UIDuser);
		        SynNodeId = resultp.get(Maori_Discover_Word_Details.SYNNID);
		        SynParentNodeId = resultp.get(Maori_Discover_Word_Details.SYNParentNID);
		        SynUserLikedSyn = resultp.get(Maori_Discover_Word_Details.SYNUserLikedSyn);
				new UploadLikeStateDetails().execute();
			}
		});
		
		setDefAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				HashMap<String, String> resultp = new HashMap<String, String>();
				resultp = data.get(position);
				Log.e("TAG", "UIDuser***:" + resultp.get(Maori_Discover_Word_Details.UIDuser));
				Log.e("TAG", "SYNNID****: " + resultp.get(Maori_Discover_Word_Details.SYNNID));
			}
		});
		return itemView;
	}
	
	private class UploadLikeStateDetails extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				JSONObject json = new JSONObject();
				httppost = new HttpPost("http://langapp.mirzabros.com/maoriapi/saveNodeLike.php");
				// Selected Type ID / content_type_id
				json.put("record1", SynNodeId);
				// Selected UID / added_by
				json.put("record2", SynUserID);
				
				json.put("record3", "0");
				
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void args) {
			Log.v("LIKE RES ", ":" + result);
			
			if (result != null) {
				arraylist = new ArrayList<HashMap<String, String>>();
				try {
					JSONObject jsonObj = new JSONObject(result);
					jsonarray = jsonObj.getJSONArray("posts");
					for (int i = 0; i < jsonarray.length(); i++) {
						JSONObject c = jsonarray.getJSONObject(i);
						HashMap<String, String> map = new HashMap<String, String>();
					    String LikeCount =  c.getString("TotalsLikesSyn");
					    String ActiveState =  c.getString("LikeActive");
					    
					    if(ActiveState.equals("100")){
					    	setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_inactive,
									0, 0, 0);
					    	setLikeAction.setText("Like(" + LikeCount +")");
					    }
					    
					    else{
					    	setLikeAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like_h,
									0, 0, 0);
					    	setLikeAction.setText("Like(" + LikeCount +")");
					    }
						
					}
				}
				catch(Exception e){
					
				}
			}
		}
	}
}
